<template>
  <div v-loading="loading">
    <el-row :gutter="10">
      <el-col
        :span="10"
        style="text-align:left"
      >
        <el-switch
          v-model="tableDatas.filters.state"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          :active-value="1"
          :inactive-value="0"
          active-text="已打印"
          inactive-text="未打印"
          @change="getTableDatas"
        />
        <el-button
          type="primary"
          @click="getTableDatas"
        >刷新</el-button>
        <el-button
          type="success"
          @click="printBtnClick"
        >打印</el-button>
        <el-button
          type="info"
          @click="exportBtnClick"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加':'修改'"
      top="5vh"
    >
      <el-scrollbar max-height="70vh">
        <el-form :model="dialogDatas.currentData">
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
          >
            <el-date-picker
              v-if="item.isDate"
              v-model="dialogDatas.currentData[item.value]"
              :type="item.dateOption ? item.dateOption.type : 'date'"
              :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
              :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
              :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
              :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
            />
            <el-switch
              v-else-if="item.isSwitch"
              v-model="dialogDatas.currentData[item.value]"
              inline-prompt
              active-text="启用"
              inactive-text="不启用"
              :active-value="item.trueValue"
              :inactive-value="item.falseValue"
            />
            <el-input
              v-else
              v-model="dialogDatas.currentData[item.value]"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-table
      class="marginTop10"
      :data="tableDatas.tableDatasAfterPage"
      stripe
      border
      empty-text="无数据"
      max-height="30vh"
      @selection-change="tableDatas.selectionChange"
    >
      <el-table-column
        v-for="column in tableDatas.tableColumns"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
        :type="column.type"
      >
        <template
          #default="scope"
          v-if="column.prop =='operate'"
        >
          <div>
            <el-button
              type="success"
              @click="tableDatas.editBtnClick(scope.row)"
            >修改</el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="确定删除该条记录?"
              @confirm="tableDatas.deleteBtnClick(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-table
      class="marginTop10"
      :data="tableDatas.subTableDatasAfterGroupby"
      stripe
      border
      empty-text="无数据"
      max-height="70vh"
    >
      <el-table-column
        v-for="column in tableDatas.subTableColumns"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
        :type="column.type"
      />
    </el-table>
    <!-- <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination> -->

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';
import myAxios from '@/myAxios/myAxios';
import { showWarning } from '@/hooks/useMyMessageBox';
import router from '@/router';
import useMyXlsx from '@/hooks/useMyXlsx';
import { dayjs } from 'element-plus';

export default {
  name: 'ApplySHRecordView',
  setup () {
    let loading = ref(false);
    let addBtnClick = function () {
      showFormDialog();
    };

    let showFormDialog = function (row) {
      if (row) {
        dialogDatas.isNew = false;
        dialogDatas.currentData = { ...row };
      }
      else {
        dialogDatas.isNew = true;
        dialogDatas.currentData = {};
      }
      dialogDatas.dialogFormVisible = true;
    };

    let dialogDatas = reactive({
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
        {
          "value": "APPLYNO",
          "label": "领料单号",
          "isDate": false
        },
        {
          "value": "STATE",
          "label": "状态",
          "isDate": false
        },
        {
          "value": "PUSHTIME",
          "label": "损耗推送时间",
          "isDate": false
        },
        {
          "value": "DONETIME",
          "label": "损耗完成时间",
          "isDate": false
        },
        {
          "value": "DATE_TIME",
          "label": "精确到秒的时间(示例,可删除)",
          "isDate": true,
          "dateOption": {
            "type": "datetime",
            "format": "YYYY/MM/DD HH:mm:ss",
            "dateFormat": "YYYY/MM/DD",
            "timeFormat": "HH:mm:ss",
            "valueFormat": "YYYY/MM/DD HH:mm:ss"
          }
        }
      ],
      confirmBtnClick: function () {
        loading.value = true;

        let params = `${dialogDatas.currentData.APPLYNO}`
          + `🈹${dialogDatas.currentData.STATE}`
          + `🈹${dialogDatas.currentData.PUSHTIME}`
          + `🈹${dialogDatas.currentData.DONETIME}`;
        myAxios.post('添加或更新', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交成功!' + res
            });
            getTableDatas();
          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('更新失败err!' + err);
        });

      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = function () {
      loading.value = true;

      let params = `🈹${tableDatas.filters.state}`;
      myAxios.get('陈帅廷查询贴片线损耗记录', params).then(res => {
        if (res instanceof Array) {
          loading.value = false;
          tableDatas.oritableData = [...res];
          // tableDatas.oritableData = [...res, ...res, ...res, ...res, ...res, ...res];
          // ElMessage({
          //   showClose: true,
          //   type: 'success',
          //   message: '最新数据获取成功!'
          // });
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };

    onMounted(() => {
      getTableDatas();
    });

    let tableDatas = reactive({
      //表格筛选展示相关代码
      filters: {
        state: 0,

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableDatasAfterFilter: computed(() => {
        let fData = tableDatas.oritableData;
        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        // fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),

      subTableColumns: [
        {
          "type": "index",
          "width": "55",
          "label": "序号",
          "align": "center",
        },
        // {
        //   "prop": "APPLYNO",
        //   "label": "领料单号",
        //   "align": "center"
        // },
        // {
        //   "prop": "PM_MATERIALID",
        //   "label": "物料ID",
        //   "align": "center"
        // },
        {
          "prop": "MATCODE",
          "label": "物料编码",
          "align": "center"
        },
        {
          "prop": "MATNAME",
          "label": "物料名称",
          "align": "center"
        },
        {
          "prop": "QTY",
          "label": "需求数量",
          "align": "center"
        },
        // {
        //   "prop": "SENDQTY",
        //   "label": "已发送数量",
        //   "align": "center"
        // },
        // {
        //   "prop": "NEEDSAP",
        //   "label": "需求数量",
        //   "align": "center"
        // },
        {
          "prop": "CKQTY",
          "label": "出库数量",
          "align": "center"
        },
        {
          "prop": "FLQTY",
          "label": "发料数量",
          "align": "center"
        },
        {
          "prop": "TKQTY",
          "label": "退库数量",
          "align": "center"
        },
        {
          "prop": "SHQTY",
          "label": "损耗数量",
          "align": "center"
        },

      ],
      subOriTableDatas: [],
      subTableDatasAfterGroupby: computed(() => {
        let fData = JSON.parse(JSON.stringify(tableDatas.subOriTableDatas));
        //用PM_MATERIALID,MATCODE,MATNAME进行GROUPBY,把其他的值加起来,用新arr来接
        let newArr = [];
        fData.forEach(el => {
          let groupbyKey = el.PM_MATERIALID + el.MATCODE + el.MATNAME;
          let groupbyObj = newArr.find(el2 => el2.groupbyKey == groupbyKey);
          if (groupbyObj) {
            groupbyObj.QTY += el.QTY;
            groupbyObj.SENDQTY += el.SENDQTY;
            groupbyObj.NEEDSAP += el.NEEDSAP;
            groupbyObj.CKQTY += el.CKQTY;
            groupbyObj.FLQTY += el.FLQTY;
            groupbyObj.TKQTY += el.TKQTY;
            groupbyObj.SHQTY += el.SHQTY;
          }
          else {
            let newObj = {
              ...el,
              groupbyKey: groupbyKey
            };
            newArr.push(newObj);
          }
        });
        newArr = newArr.filter(el => el.SHQTY > 0);
        return newArr;
      }),

      tableColumns: [
        {
          "type": "index",
          "width": "55",
          "label": "序号",
          "align": "center",
        },
        {
          "type": "selection",
          "width": "55",
          "align": "center",
        },
        {
          "prop": "APPLYNO",
          "label": "领料单号",
          "align": "center"
        },
        {
          "prop": "ORDERNO",
          "label": "订单号",
          "align": "center"
        },
        {
          "prop": "STATE",
          "label": "状态",
          "align": "center"
        },
        {
          "prop": "PUSHTIME",
          "label": "损耗推送时间",
          "align": "center"
        },
        {
          "prop": "DONETIME",
          "label": "损耗完成时间",
          "align": "center"
        },
        // {
        //   "prop": "operate",
        //   "label": "操作",
        //   "align": "center",
        //   "width": 170,
        // },
      ],
      oritableData: [],
      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;

        let params = `${dialogDatas.currentData.APPLYNO}`;
        myAxios.post('删除', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '删除成功!' + res
            });
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },
      selectionChange: function (newSelcetion) {
        console.log('newSelcetion :>> ', newSelcetion);
        //取出数组中每一项的APPLYNO
        let applynoList = newSelcetion.map(item => item.APPLYNO);
        //转成字符串,用','分割
        let applynoStr = applynoList.join('\',\'');
        lastApplynoStr = applynoStr;

        loading.value = true;
        if (applynoStr) {
          myAxios.get('陈帅廷查询贴片线领料单物料损耗', applynoStr).then(res => {
            if (res instanceof Array) {
              loading.value = false;
              tableDatas.subOriTableDatas = [...res];
              // tableDatas.oritableData = [...res, ...res, ...res, ...res, ...res, ...res];
              ElMessage({
                showClose: true,
                type: 'success',
                message: '数据获取成功!'
              });
            }
            else {
              loading.value = false;
              showWarning('获取数据失败res!' + res);
            }
          }).catch((err) => {
            loading.value = false;
            showWarning('获取数据失败err!' + err);
          });
        }
        else {
          loading.value = false;
          tableDatas.subOriTableDatas = [];
        }
      },
    });

    let lastApplynoStr = '';
    let printBtnClick = function () {
      //如果是未打印状态,把打印状态更新为已打印,然后再打开网页
      if (tableDatas.filters.state == 0) {
        loading.value = true;
        let params = `${lastApplynoStr}🈹1`;
        myAxios.post('陈帅廷更新贴片线损耗单状态', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            // dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交成功!' + res
            });
            getTableDatas();

            //跳转到打印页面
            const href = router.resolve({
              path: '/applySH/applySHPrint',
              query: { applynoStr: lastApplynoStr, type: '1' }
            });
            window.open(href.href, '_blank');
            // router.push({ path: '/applySH/applySHPrint', query: { applynoStr: lastApplynoStr, type: '1' } });
          }
          else {
            loading.value = false;
            showWarning('提交失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('提交失败err!' + err);
        });
      }
      //如果是已打印状态,直接打开打印页面
      else if (tableDatas.filters.state == 1) {
        //跳转到打印页面
        const href = router.resolve({
          path: '/applySH/applySHPrint',
          query: { applynoStr: lastApplynoStr, type: '1' }
        });
        window.open(href.href, '_blank');
        // router.push({ path: '/applySH/applySHPrint', query: { applynoStr: lastApplynoStr, type: '1' } });
      }
    };

    let exportBtnClick = function () {
      let exportDatas = JSON.parse(JSON.stringify(tableDatas.subTableDatasAfterGroupby.filter(el => el.SHQTY > 0)));
      if (!exportDatas.length) {
        showWarning('没有数据可导出!');
        return;
      }
      let xlsx = useMyXlsx();
      let exportOption = {
        titles: {
          'MATCODE': '物料号',
          'MATNAME': '物料描述',
          'SHQTY': '数量',
        },
        header: ['MATCODE', 'MATNAME', 'SHQTY'],
      };
      exportOption.hideColumns = Object.keys(exportDatas[0]).filter(key => !exportOption.header.includes(key));
      let nowStr = new dayjs().format('YYYYMMDDHHmmss');
      xlsx.exportDatas(exportDatas, exportOption, nowStr + '.xls');

    };

    return {
      loading,
      getTableDatas,
      dialogDatas,
      tableDatas,
      printBtnClick,
      exportBtnClick
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

